#include <stdint.h>
#include "tool.h"
#include <stdio.h>
#include <string.h>

uint16_t get_crc(uint8_t* pack, uint16_t length) {
    uint16_t crc_reg = 0xFFFF;
    uint16_t multi = 0xa001;
    //	uint16_t tmp = 0;
    int i, t;

    //printf("len=%d\n", len);
    for (i = 0; i < length; i++) {
        crc_reg ^= ((uint16_t)pack[i]);
        for (t = 0; t < 8; t++) {						//重复右移8次
            ((crc_reg & 0x01) == 0x01) ? (crc_reg = (crc_reg >> 1) ^ multi) : (crc_reg >>= 1);
        }
    }
    //	tmp = (crc_reg >> 8) & 0x00ff;
    //	return (crc_reg << 8) | tmp;		//结果 颠倒高8低8
    return crc_reg;
}
uint16_t get_sum(uint8_t* pack, uint16_t length){
    uint16_t sum=0;
    for(int i=0; i<length;i++){
        sum+=pack[i];
    }
    return sum;
}

uint16_t u8_2_u16(uint8_t* dat){			//拼接2个char为int
    return (uint16_t)dat[0]<<8|(uint16_t)dat[1];
}

//（hex串 => 字符串）：
void hex2str(uint8_t* in, uint8_t* out, uint16_t len) {
    for (int i = 0; i < len * 2; i += 2) {
        out[i/2]=((((in[i]-0x30)<<4)&0xf0)|(in[i+1]>=0x41?((in[i+1]-0x37)&0x0f):((in[i+1]-0x30)&0x0f)));
    }
}

//（字符串 => hex串）：
int str2hex(char* out_hex, char* in_str, int in_len) {
    int i;
    for (i = 0; i < in_len; i++) {
        sprintf(&out_hex[i * 2], "%02x", in_str[i]);
    }
    return in_len * 2;
}

int str_search(const char* src, char* dst, int num) {		//在src查找dst第n次出现的首位置
    char* tmpsrc = (char*)src;
    //int pos = 0, len = strlen(src);
    while (num--) {
        tmpsrc = strstr(tmpsrc, dst);
        if (!tmpsrc)
            return -1;
        ++tmpsrc;
    }
    return (int)(tmpsrc - src) - 1;
}

//return byte number
int str_split(char* dst_buf,char* src_str,char* head,int head_num,char* tail,int tail_num){     //拷贝一段 到目标
    int inde_head=0,inde_tail=0;
    if(0>(inde_head=str_search(src_str,head,head_num)))
        return -1;
    ++inde_head;        //到达目标后部字串 头
    if(0>(inde_tail=str_search(src_str,tail,tail_num)))
        return -1;
    strncpy(dst_buf,&src_str[inde_head],(size_t)(inde_tail-(inde_head)));
    return inde_tail-(inde_head);
}


